package com.avoid.easymqtt.remoting.common;

import com.avoid.easymqtt.common.SystemClock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 线程基类
 *
 * @author avoid@fiture.com
 * @date 2022/5/5
 * @motto Life is so short,do something to make yourself happy,such as coding
 */
public abstract class ServiceThread implements Runnable {

    private static final Logger log = LoggerFactory.getLogger(RemotingHelper.EASYMQTT_REMOTING);

    private static final long JOIN_TIME = 90 * 1000;
    protected final Thread thread;
    protected volatile boolean hasNotified = false;
    protected volatile boolean stopped = false;

    public ServiceThread() {
        this.thread = new Thread(this, this.getServiceName());
    }

    public abstract String getServiceName();

    public void start() {
        this.thread.start();
    }

    public void shutdown() {
        this.shutdown(false);
    }

    public void shutdown(final boolean interrupt) {
        this.stopped = true;
        log.info("shutdown thread " + this.getServiceName() + " interrupt " + interrupt);
        synchronized (this) {
            if (!this.hasNotified) {
                this.hasNotified = true;
                this.notify();
            }
        }

        try {
            if (interrupt) {
                this.thread.interrupt();
            }

            long beginTime = SystemClock.getNow();
            this.thread.join(this.getJointime());
            long elapsedTime = SystemClock.getNow() - beginTime;
            log.info(
                "join thread " + this.getServiceName() + " elapsed time(ms) " + elapsedTime + " " + this.getJointime());
        } catch (InterruptedException e) {
            log.error("Interrupted", e);
        }
    }

    public long getJointime() {
        return JOIN_TIME;
    }

    public boolean isStopped() {
        return stopped;
    }

}
